import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'group_member_logic.dart';

/// 群组成员管理页面
class GroupMemberView extends GetView<GroupMemberLogic> {
  const GroupMemberView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        backgroundColor: Colors.black,
        elevation: 0,
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios, color: Colors.white, size: 20.sp),
          onPressed: () => Get.back(),
        ),
        title: Obx(() => Text(
              controller.state.groupName.value,
              style: TextStyle(
                fontSize: 18.sp,
                fontWeight: FontWeight.w600,
                color: Colors.white,
              ),
            )),
        centerTitle: true,
        actions: [
          // 群主才显示成员管理按钮
          Obx(() {
            if (!controller.state.isCreator.value) return const SizedBox.shrink();
            return IconButton(
              icon: Icon(
                controller.state.isEditMode.value ? Icons.check : Icons.delete_outline,
                color: Colors.white,
                size: 24.sp,
              ),
              onPressed: controller.toggleEditMode,
            );
          }),
        ],
      ),
      body: Obx(() {
        if (controller.state.isLoading.value) {
          return const Center(
            child: CircularProgressIndicator(color: Colors.white),
          );
        }

        return SingleChildScrollView(
          padding: EdgeInsets.all(20.w),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 成员列表标题
              Text(
                controller.state.isCreator.value ? '成员管理' : '成员列表',
                style: TextStyle(
                  fontSize: 18.sp,
                  fontWeight: FontWeight.w600,
                  color: Colors.white,
                ),
              ),
              SizedBox(height: 16.h),

              // 成员列表
              ...controller.state.memberList.map((member) {
                return _buildMemberCard(member);
              }).toList(),

              SizedBox(height: 32.h),

              // 群主才显示添加成员部分
              Obx(() {
                if (!controller.state.isCreator.value) return const SizedBox.shrink();
                return Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 添加群组成员标题
                    Text(
                      '添加群组成员',
                      style: TextStyle(
                        fontSize: 18.sp,
                        fontWeight: FontWeight.w600,
                        color: Colors.white,
                      ),
                    ),
                    SizedBox(height: 16.h),

                    // 邀请输入框
                    Container(
                padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 4.h),
                decoration: BoxDecoration(
                  color: const Color.fromARGB(255, 54, 54, 54),
                  borderRadius: BorderRadius.circular(25.r),
                  border: Border.all(
                    color: const Color.fromARGB(255, 92, 92, 92),
                    width: 0.5,
                  ),
                ),
                child: Row(
                  children: [
                    Expanded(
                      child: TextField(
                        controller: controller.inviteController,
                        style: TextStyle(
                          fontSize: 14.sp,
                          color: Colors.white,
                        ),
                        decoration: InputDecoration(
                          hintText: '通过手机/邮箱搜索',
                          hintStyle: TextStyle(
                            fontSize: 14.sp,
                            color: Colors.grey[400],
                          ),
                          border: InputBorder.none,
                          contentPadding: EdgeInsets.symmetric(
                            horizontal: 0,
                            vertical: 12.h,
                          ),
                        ),
                        keyboardType: TextInputType.emailAddress,
                      ),
                    ),
                    GestureDetector(
                      onTap: controller.inviteMember,
                      child: Container(
                        padding: EdgeInsets.symmetric(
                            horizontal: 24.w, vertical: 8.h),
                        decoration: BoxDecoration(
                          color: Colors.black,
                          borderRadius: BorderRadius.circular(20.r),
                          border: Border.all(
                    color: const Color.fromARGB(255, 92, 92, 92),
                    width: 0.5,
                  ),
                        ),
                        child: Text(
                          '邀请',
                          style: TextStyle(
                            fontSize: 14.sp,
                            color: Colors.white,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
                    ),

                    SizedBox(height: 24.h),

                    // 通过邀请码加入
                    Text(
                      '通过邀请码加入亲人守护群组',
                      style: TextStyle(
                        fontSize: 14.sp,
                        color: Colors.white,
                      ),
                    ),
                    SizedBox(height: 16.h),

                    // 二维码区域
                    Center(
                      child: Container(
                        padding: EdgeInsets.all(5.w),
                        decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(12.r),
                        ),
                        child: Obx(() {
                          final groupCode = controller.state.groupCode.value;
                          if (groupCode.isEmpty) {
                            return Container(
                              width: 150.w,
                              height: 150.w,
                              color: Colors.grey[300],
                              child: Center(
                                child: Text(
                                  '暂无群组码',
                                  style: TextStyle(
                                    fontSize: 14.sp,
                                    color: Colors.grey[600],
                                  ),
                                ),
                              ),
                            );
                          }
                          return QrImageView(
                            data: groupCode,
                            version: QrVersions.auto,
                            size: 150.w,
                            backgroundColor: Colors.white,
                          );
                        }),
                      ),
                    ),

                    SizedBox(height: 16.h),

                    // 群组码文字
                    Center(
                      child: Obx(() => Text(
                            '群组码：${controller.state.groupCode.value}',
                            style: TextStyle(
                              fontSize: 14.sp,
                              color: Colors.white,
                              fontWeight: FontWeight.w500,
                            ),
                          )),
                    ),

                    SizedBox(height: 8.h),

                    // 提示文字
                    Center(
                      child: Text(
                        '使用AZring APP 扫描此二维码，即可加入家庭圈',
                        style: TextStyle(
                          fontSize: 12.sp,
                          color: Colors.grey[500],
                        ),
                        textAlign: TextAlign.center,
                      ),
                    ),

                    SizedBox(height: 20.h),

                    // 解散群组按钮
                    Center(
                      child: GestureDetector(
                        onTap: controller.dismissGroup,
                        child: Container(
                          width: double.infinity,
                          padding: EdgeInsets.symmetric(vertical: 16.h),
                          decoration: BoxDecoration(
                            color: Color(0xff252825),
                            borderRadius: BorderRadius.circular(25.r),
                            border: Border.all(
                              color: const Color.fromARGB(255, 92, 92, 92),
                              width: 0.5,
                            ),
                          ),
                          child: Center(
                            child: Text(
                              '解散群组',
                              style: TextStyle(
                                fontSize: 16.sp,
                                color: Colors.white,
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),

                    SizedBox(height: 32.h),
                  ],
                );
              }),

              // 普通成员显示退出群组按钮
              Obx(() {
                if (controller.state.isCreator.value) return const SizedBox.shrink();
                return Center(
                  child: GestureDetector(
                    onTap: controller.leaveGroup,
                    child: Container(
                      width: double.infinity,
                      padding: EdgeInsets.symmetric(vertical: 16.h),
                      decoration: BoxDecoration(
                        color: Color(0xff252825),
                        borderRadius: BorderRadius.circular(25.r),
                        border: Border.all(
                          color: const Color.fromARGB(255, 92, 92, 92),
                          width: 0.5,
                        ),
                      ),
                      child: Center(
                        child: Text(
                          '退出群组',
                          style: TextStyle(
                            fontSize: 16.sp,
                            color: Colors.white,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ),
                    ),
                  ),
                );
              }),

              SizedBox(height: 40.h),
            ],
          ),
        );
      }),
    );
  }

  /// 成员卡片
  Widget _buildMemberCard(Map<String, dynamic> member) {
    final memberName = member['memberName'] ?? '未知用户';
    final memberAccount =
        member['memberAccount'] ?? member['userId']?.toString() ?? '';
    final memberAvatar = member['memberAvatar'] ?? '';
    final memberType = member['memberType'] ?? '2';
    final isCreator = memberType == '1';

    // 处理头像URL
    final avatarUrl = memberAvatar.isNotEmpty
        ? (memberAvatar.startsWith('http')
            ? memberAvatar
            : 'https://api.azlg.com/prod-api$memberAvatar')
        : null;

    return Obx(() {
      final showDeleteButton = controller.state.isEditMode.value && 
                               controller.state.isCreator.value && 
                               !isCreator; // 不能删除创建者

      return Container(
        margin: EdgeInsets.only(bottom: 12.h),
        child: Stack(
          children: [
            Container(
              padding: EdgeInsets.all(16.w),
              decoration: BoxDecoration(
                color: const Color.fromARGB(255, 54, 54, 54),
                borderRadius: BorderRadius.circular(12.r),
                border: Border.all(
                  color: const Color.fromARGB(255, 87, 87, 87),
                  width: 1,
                ),
              ),
              child: Row(
                children: [
                  // 头像
                  Container(
                    width: 50.w,
                    height: 50.w,
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      color: Colors.grey[400],
                      image: avatarUrl != null
                          ? DecorationImage(
                              image: NetworkImage(avatarUrl),
                              fit: BoxFit.cover,
                            )
                          : null,
                    ),
                    child: avatarUrl == null
                        ? Icon(
                            Icons.person,
                            size: 24.sp,
                            color: Colors.grey[600],
                          )
                        : null,
                  ),
                  SizedBox(width: 12.w),

                  // 名称和ID
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          children: [
                            Text(
                              memberName,
                              style: TextStyle(
                                fontSize: 16.sp,
                                fontWeight: FontWeight.w600,
                                color: Colors.white,
                              ),
                            ),
                            if (isCreator) ...[
                              SizedBox(width: 8.w),
                              Container(
                                padding: EdgeInsets.symmetric(
                                    horizontal: 8.w, vertical: 2.h),
                                decoration: BoxDecoration(
                                  color: const Color(0xFFED5C2F),
                                  borderRadius: BorderRadius.circular(4.r),
                                ),
                                child: Text(
                                  '创建者',
                                  style: TextStyle(
                                    fontSize: 10.sp,
                                    color: Colors.white,
                                    fontWeight: FontWeight.w500,
                                  ),
                                ),
                              ),
                            ],
                          ],
                        ),
                        SizedBox(height: 4.h),
                        Text(
                          'ID：$memberAccount',
                          style: TextStyle(
                            fontSize: 14.sp,
                            color: Colors.grey[400],
                          ),
                        ),
                      ],
                    ),
                  ),

                  // 修改备注按钮
                  GestureDetector(
                    onTap: () => controller.editRemark(member),
                    child: Container(
                      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
                      decoration: BoxDecoration(
                        color: const Color.fromARGB(255, 66, 66, 66),
                        borderRadius: BorderRadius.circular(20.r),
                      ),
                      child: Text(
                        '修改备注',
                        style: TextStyle(
                          fontSize: 12.sp,
                          color: Colors.white,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),

            // 删除按钮（编辑模式下显示）
            if (showDeleteButton)
              Positioned(
                top: 0,
                right: 0,
                child: GestureDetector(
                  onTap: () => controller.removeMember(member),
                  child: Container(
                    width: 28.w,
                    height: 28.w,
                    decoration: BoxDecoration(
                      color: Colors.red,
                      shape: BoxShape.circle,
                      border: Border.all(
                        color: const Color.fromARGB(255, 54, 54, 54),
                        width: 2,
                      ),
                    ),
                    child: Icon(
                      Icons.close,
                      color: Colors.white,
                      size: 16.sp,
                    ),
                  ),
                ),
              ),
          ],
        ),
      );
    });
  }
}
